package com.uziot.bucket.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import java.lang.reflect.Field;
import java.util.LinkedHashMap;

/**
 * @author shidt
 * @version V1.0
 * @className ToStringUtils
 * @date 2020-05-12 21:08:05
 * @description
 */

public class ToStringUtils {
    /**
     * 重写toString()方法，美化字段的输出
     *
     * @param t   t
     * @param <T> st
     * @return str
     */
    public static <T> String toString(T t) {
        // 获取实体类的所有属性，返回Field数组
        Field[] fields = t.getClass().getDeclaredFields();
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                map.put(field.getName(), field.get(t));
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        ToStringBuilder builder = new ToStringBuilder(t, ToStringStyle.MULTI_LINE_STYLE);
        map.forEach(builder::append);
        return builder.toString();
    }

    /**
     * 美化JSON输出，一般用于打印日志
     *
     * @param obj obj
     * @return str
     */
    public static String prettyJson(Object obj) {
        SerializerFeature prettyFormat = SerializerFeature.PrettyFormat;
        SerializerFeature writeMapNullValue = SerializerFeature.WriteMapNullValue;
        SerializerFeature writeDateUseDateFormat = SerializerFeature.WriteDateUseDateFormat;
        return JSON.toJSONString(obj, prettyFormat, writeMapNullValue, writeDateUseDateFormat);
    }
}